package kubeutilscorev1

import (
	"context"
	"go-kube-mgr/utils/kubeutils/kubeutils"
	"go-kube-mgr/utils/logs"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	typedv1 "k8s.io/client-go/kubernetes/typed/core/v1"
)

type Service struct {
	InstanceInterface typedv1.CoreV1Interface
	Item              *corev1.Service
}

func NewService(kubeconfig string, service *corev1.Service) *Service {
	instance := kubeutils.ResourceInstance{}
	instance.Init(kubeconfig)
	return &Service{
		InstanceInterface: instance.Clientset.CoreV1(),
		Item:              service,
	}
}

func (s *Service) Create(namespace string) error {
	logs.Info(map[string]interface{}{"名称": s.Item.Name, "命名空间": namespace}, "创建service")
	_, err := s.InstanceInterface.Services(namespace).Create(context.TODO(), s.Item, metav1.CreateOptions{})
	return err
}

func (s *Service) Update(namespace string) error {
	logs.Info(map[string]interface{}{"名称": s.Item.Name, "命名空间": namespace}, "更新service")
	_, err := s.InstanceInterface.Services(namespace).Update(context.TODO(), s.Item, metav1.UpdateOptions{})
	return err
}

func (s *Service) Delete(namespace string, name string, gracePeriodSecods *int64) error {
	logs.Info(map[string]interface{}{"名称": name, "命名空间": namespace}, "删除service")
	deleteoptions := metav1.DeleteOptions{
		GracePeriodSeconds: gracePeriodSecods,
	}
	err := s.InstanceInterface.Services(namespace).Delete(context.TODO(), name, deleteoptions)
	return err
}

func (s *Service) DeleteList(namespace string, namelist []string, gracePeriodSecods *int64) error {
	for _, name := range namelist {
		s.Delete(namespace, name, gracePeriodSecods)
	}
	return nil
}

func (s *Service) List(namespace string, labelSelector string, fieldSelector string) (interface{}, error) {
	logs.Info(map[string]interface{}{"命名空间": namespace}, "获取service列表")
	listoptions := metav1.ListOptions{
		LabelSelector: labelSelector,
		FieldSelector: fieldSelector,
	}
	i, err := s.InstanceInterface.Services(namespace).List(context.TODO(), listoptions)
	return i.Items, err
}

func (s *Service) Get(namespace string, name string) (interface{}, error) {
	logs.Info(map[string]interface{}{"名称": name, "命名空间": namespace}, "获取service详情")
	i, err := s.InstanceInterface.Services(namespace).Get(context.TODO(), name, metav1.GetOptions{})
	i.APIVersion = "v1"
	i.Kind = "Service"
	return i, err
}
